package com.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 这个类需要实现Servlet接口，需要实现Servlet的方法
 */
public class HelloServlet implements Servlet {
    public HelloServlet() {
        System.out.println("1、构造器方法");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2、init()初始化方法");
        //1、可以获取 Servlet 程序的别名 servlet-name 的值
        System.out.println("HelloServlet的别名是"+servletConfig.getServletName());//获取 servlet-name 的值，默认是类名

        //2、获取初始化参数 init-param
        System.out.println("初始化参数username的值"+servletConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值"+servletConfig.getInitParameter("url"));
    }
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    //service()方法，是专门用来处理请求和响应的
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
//        System.out.println("3、service方法");
        //类型转换（因为ServletRequest子类HttpServletRequest有getMethod()）
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取请求方式
        String method = httpServletRequest.getMethod();
        //处理不同的请求
        if ("GET".equals(method)){
            doGet();
        }else if("POST".equals(method)){
            doPost();
        }
    }
    //做get请求
    public void doPost(){
        System.out.println("post请求");
    }
    //做post请求
    public void doGet(){
        System.out.println("get请求");
    }

    @Override
    public String getServletInfo() {
        return null;
    }
    @Override
    public void destroy() {
        System.out.println("4、destroy销毁方法");
    }
}
